<template>
  <div style="display: flex; flex-direction: column; flex: 1">
    <div>
      <el-button type="primary" @click="addClick()">新增</el-button>
    </div>
    <div style="flex: 1">
      <el-dialog
        v-model="dialogVisible"
        :title="addOrModifyRole"
        width="500"
        :before-close="handleClose"
      >
        <el-form
          :label-position="labelPosition"
          label-width="auto"
          v-model="tableKeysList2"
        >
          <el-form-item
            v-for="(ite, ind) in tableKeysList2"
            :key="ind"
            :label="ite.value"
          >
            <div style="display: flex; width: 100%">
              <el-input v-model="ite.lable" />
              <el-button type="info" @click="clickRandom(ite.value)"
                >随机生成</el-button
              >
            </div>
          </el-form-item>

          <!-- <el-form-item label="Activity zone">
          <el-input v-model="tableKeys.tabkeys.region" />
        </el-form-item>
        <el-form-item label="Activity form">
          <el-input v-model="tableKeys.tabkeys.type" />
        </el-form-item> -->
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisiblecancel">取消</el-button>
            <el-button type="primary" @click="AdddialogVisible">
              确认
            </el-button>
          </div>
        </template>
      </el-dialog>
      <el-divider />
      <!--  :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)" -->
      <el-table
        :data="
          tableData.list.slice(
            (currentPage - 1) * pageSize,
            currentPage * pageSize
          )
        "
      >
        <el-table-column
          v-for="(item, index) in tableKeys.tabkeys"
          :key="index + 1"
          fixed
          :prop="item"
          :label="item"
          :fit="true"
          :min-width="$getTableColumnWidth(item, tableData.list)"
        />

        <!-- <el-table-column prop="userName" label="userName" width="100" />
      <el-table-column prop="pass" label="pass" />
      <el-table-column prop="token" label="token" width="520" /> -->
        <!-- <el-table-column prop="address" label="Address" width="600" /> -->
        <!-- <el-table-column prop="zip" label="Zip" width="120" /> -->
        <el-table-column
          fixed="right"
          label="Operations"
          :min-width="tableMinWith"
        >
          <template #default="scope">
            <div
              class="optionDiv"
              style="white-space: nowrap; display: inline-block"
            >
              <el-button
                type="danger"
                size="small"
                @click="handleClick(scope.row)"
              >
                删除
              </el-button>

              <el-button
                type="primary"
                size="small"
                @click="handleClickEdit(scope.row)"
                >编辑</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="demo-pagination-block">
        <div class="demonstration">分页</div>
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[5, 10, 20, 30, 40]"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.list.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, onBeforeUpdate } from "vue";
import {
  apiLogUsers,
  apiAddressUsers,
  apiDeleteUsers,
  apiEditingUsers,
} from "@/utils/api";
// 获取全局变量
import { getCurrentInstance } from "vue";

const instance = getCurrentInstance();
// 状态管理 pina  composition API模式
import { useCounterStore } from "@/stores/counter.js";
// 表格操作列表宽度
const tableMinWith = ref(0);
tableMinWith.value = instance.proxy.$getOperatorWidth();
// 分页
const currentPage = ref(1);
const totalList = ref(0);
const pageSize = ref(5);
const small = ref(false);
const background = ref(false);
const disabled = ref(false);

// composition API模式
const counterStore = useCounterStore();
counterStore.footerTitle = reactive({
  one: "故人西辞黄鹤楼，烟花三月下扬州。孤帆远影碧空尽，唯见长江天际流。 ",
  tow: " 黄鹤楼送孟浩然之广陵---李白·唐",
});
// console.log(counterStore.userNamePass.userName, "userNamePass");

// 想结构赋值的话，需要导入 storeToRefs 函数，将解构出来的参数变成响应式:
// import { storeToRefs } from 'pinia'
// import { useCounterStore } from "@/stores/counter";

// const counterStore = useCounterStore()
// // 将解构出来的参数变成响应式
// const { count, doubleCount } = storeToRefs(counterStore)
// // 作为 action 的 increment 和 decrement 可以直接解构
// const { increment, decrement } = counterStore
// 获取所有角色
let tableData = reactive({ list: [] });
let tableKeys = reactive({ tabkeys: [] });
const addOrModifyRole = ref("");
const okId = ref("");
let tableKeysList = reactive([]);
let tableKeysList2 = reactive([]);
let dialogVisible = ref(false); //弹窗的显示隐藏
// 获取表格数据
const getApiTable = apiLogUsers().then((res: any) => {
  console.log(res.data.status, res, "resresresresres");
  if (res.status == 200) {
    console.log(222);

    // 表格数据
    tableData.list = res.data;
    // 获取数组对象里面的键key和值value对象键值
    tableKeys.tabkeys = Object.keys(res.data[0]);
  }
});
// 随机生成
const clickRandom = (val: any) => {
  console.log(val);
};

const tableKeysLists = () => {
  console.log(tableKeysList, 221111);
  if (tableKeysList.length == 0) {
    let removedArr = tableKeys.tabkeys.filter((x: string) => x !== "id");

    for (var i = 0; i < removedArr.length; i++) {
      tableKeysList.push({ value: "", lable: "" });
      tableKeysList[i].value = removedArr[i];
      tableKeysList2 = tableKeysList;
    }
  } else {
    for (var i = 0; i < tableKeysList.length; i++) {
      tableKeysList[i].lable = "";
      tableKeysList2 = tableKeysList;
    }
  }

  return tableKeysList2;
};
// 删除
const handleClick = (id: any) => {
  apiDeleteUsers(id.id).then((res: any) => {
    console.log(res);

    location.reload();
  });
};
// 编辑
const handleClickEdit = (e: any) => {
  okId.value = e.id;
  addOrModifyRole.value = "修改角色";
  let edata = JSON.parse(JSON.stringify(e));
  const { id, ...edata3 } = edata;
  let edata2 = reactive([]);
  for (let i in edata3) {
    edata2.push({ value: i, lable: edata3[i] });
    // edata2[i].value = i;
    // edata2[i].lable = edata[i];
  }
  tableKeysList2 = edata2;
  tableKeysList = edata2;
  // let removedArr = edata.filter((x: string) => x !== "id");
  // console.log(removedArr, "removedArr");

  // let eList = reactive([]);
  // for (var i = 0; i < removedArr.length; i++) {
  //   eList.push({ value: "", lable: "" });
  //   eList[i].value = removedArr[i];
  //   tableKeysList2 = eList;
  //   console.log(tableKeysList2, "arr32222");
  // }

  // tableKeysList2.push(e);
  // tableKeysList2 = eList;
  dialogVisible.value = true;
};
// 新增
const addClick = () => {
  okId.value = "";
  addOrModifyRole.value = "新增角色";
  tableKeysLists();
  dialogVisible.value = true;
};

// 确定提交
const AdddialogVisible = () => {
  dialogVisible.value = false;

  let userList = reactive({});
  console.log(tableKeysList, "tableKeysList");

  for (var i = 0; i < tableKeysList.length; i++) {
    userList[tableKeysList[i].value] = tableKeysList[i].lable;
  }
  console.log(tableKeysList, "tableKeysList333");

  // 如果有空，就提示
  console.log(userList, "userList2323232");

  if (getValue(userList)) {
    console.log(getValue(userList), "getValue(userList)");

    // 如果okId为真，就是编辑
    if (okId.value) {
      console.log(userList, "0000");
      let id = okId.value;
      let data = userList;
      apiEditingUsers({ id, data }).then((res: any) => {
        console.log(res, "新增");
        location.reload();
      });
    } else {
      // 否则就是新增
      console.log(userList, "userListuserListuserList");
      const data = userList;
      apiAddressUsers(data).then((res: any) => {
        console.log(3333);

        location.reload();
        // console.log(res, "userListuserListuserListuserList");
      });
    }
  } else {
    console.log("you有对象为空");
  }
};
// 取消
const dialogVisiblecancel = () => {
  tableKeysLists();
  // tableKeys.tabkeys = []提交成功后清除数组内容

  dialogVisible.value = false;
};
import type { FormProps } from "element-plus";

const labelPosition = ref<FormProps["labelPosition"]>("right");

import { ElMessageBox } from "element-plus";
// import { el } from "element-plus/es/locale";

const handleClose = (done: () => void) => {
  ElMessageBox.confirm("您确定要关闭此对话框吗?")
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
};

// 分页

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  pageSize.value = val;
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  currentPage.value = val;
};

// 判断对象里面的每个key值是否为空  公共方法
const getValue = (object: object) => {
  let number = ref(0);
  let number2 = ref(0);
  Object.keys(object).forEach((el) => {
    number.value++;
    if (object[el] !== null && object[el] !== "") {
      number2.value++;
    }
  });

  if (number.value == number2.value) {
    return true;
  } else {
    return false;
  }
};
</script>

<style lang="scss" scoped>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>
